"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.User = void 0;
const MySQLService_1 = __importDefault(require("../service/MySQLService"));
const Mgr_1 = __importDefault(require("./Mgr"));
const Room_1 = require("./Room");
class User {
    constructor(connection) {
        this.score = 100;
        this.is_onLine = true; //是否在线
        this.is_die = false; //对局中是否已经死亡
        this.connection = connection;
        this.heartBeat();
        //收到消息
        connection.on('text', this.onMessage.bind(this));
        //关闭监听
        connection.on('close', this.onDropLine.bind(this));
        //掉线监听
        connection.on('error', this.onDropLine.bind(this));
    }
    sendObj(obj) {
        this.connection.sendText(JSON.stringify(obj));
    }
    /**
     * 收到的message
     * isRoom   是否是房间内消息
     * type     data类型
     * data     数据
     */
    onMessage(result) {
        console.log("onMessage: " + result);
        let obj = JSON.parse(result);
        if (obj.isRoom) {
            this.room.reciveObj(this, obj);
        }
        else {
            switch (obj.method) {
                case "userBind":
                    this.userBind(obj);
                    break;
                case "match":
                    Mgr_1.default.match(this);
                    break;
                case "createOrjoinRoom":
                    Mgr_1.default.createOrjoinRoom(this, obj.data.cipher);
                    break;
                case "watchingRoom":
                    Mgr_1.default.watchingRoom(this, obj.data);
                    break;
                case "cancel_match":
                    this.room.cancelMatch(this);
                    break;
                default: console.error("webSocket 收到未知方法");
            }
        }
    }
    /** 用户下线，修改登录状态 */
    onDropLine(code) {
        if (!this.is_onLine) {
            return;
        }
        clearInterval(this.timer);
        this.is_onLine = false;
        if (this.room == null) {
            Mgr_1.default.users.delete(this.username);
        }
        else {
            if (this.room.state == Room_1.RoomState.MATCHING) {
                this.room.cancelMatch(this); //匹配中掉线
            }
            else if (this.room.state == Room_1.RoomState.GAMEING) {
                this.room.checkPlayersOnLineState(); //游戏中掉线
            }
        }
        MySQLService_1.default.updateUserLoginState(this.username, 0);
    }
    /** 用户上线，修改数据库登录状态，检测是否要进行重连 */
    userBind(obj) {
        this.username = obj.data;
        MySQLService_1.default.updateUserLoginState(this.username, 1);
        Mgr_1.default.users.set(this.username, this);
    }
    heartBeat() {
        this.timer = setInterval(() => {
            this.sendObj({ "isGame": false, "type": "heartBeat" });
        }, 5000);
    }
}
exports.User = User;
